//app.js
App({
  onLaunch: function () { // 小程序启动
    this.globalData.SystemInfo = wx.getSystemInfoSync()
    this.globalData.sysinfo = wx.getSystemInfoSync()
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
	liv_id: 'LIVL00000000000000002159',
    sysinfo: {},
    SystemInfo:{},
    BluetoothState: false, // 蓝牙适配器状态
    connectState: false // 蓝牙连接状态
  },
  getModel: function () { //获取手机型号
    return this.globalData.sysinfo["model"]
  },
  getVersion: function () { //获取微信版本号
    return this.globalData.sysinfo["version"]
  },
  getSystem: function () { //获取操作系统版本
    return this.globalData.sysinfo["system"]
  },
  getPlatform: function () { //获取客户端平台
    return this.globalData.sysinfo["platform"]
  },
  getSDKVersion: function () { //获取客户端基础库版本
    return this.globalData.sysinfo["SDKVersion"]
  },
  buf2string: function (buffer) {
    var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
    var str = ''
    for (var i = 0; i<arr.length; i++) {
    str += String.fromCharCode(arr[i])
  }
  return str
  },
  /**
   * POST 请求
   * @Param url 请求接口名称
   * @Param postData 请求参数
   */
  //  公用请求方法
  netRequest: function ({ url, data, success, method = "POST" }) {
    console.log()
    //let server = 'https://xxx.xxxxxxxx.cn';//正式域名
     let server = 'http://ws3jjmk6qw.51http.tech';//测试域名
    // 本地取存储的 sessionID
    let sessionId = wx.getStorageSync('sid'),
      that = this;
    if (sessionId != "" && sessionId != null) {
      var header = { 'content-type': 'application/json', 'Cookie': 'sid=' + sessionId };
    } else {
      var header = { 'content-type': 'application/json' };
    }
    wx.request({
      url: server + url,
      method: method,
      data: data,
      header: header,
      success: (res) => {
        if (sessionId == "" || sessionId == null) {
          wx.setStorageSync('sid', '1') //  如果本地没有就说明第一次请求 把返回的 sessionId 存入本地
        }
        let data = res.data;
        res['statusCode'] === 200 ? success(data):getApp.failResult;
        console.log(res)
      },
      fail: function (res) {
        wx.showToast({
          title: '请求超时',
          icon: 'loading',
          duration: 2000
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    });
},
failResult(){
  wx.showToast({
    title: '请求超时',
    icon: 'loading',
    duration: 100000
  })
},
hexCharCodeToStr:function(hexCharCodeStr) {
    　　var trimedStr = hexCharCodeStr.trim();
    　　var rawStr =
      　　trimedStr.substr(0, 2).toLowerCase() === "0x"
        　　?
        　　trimedStr.substr(2)
        　　:
        　　trimedStr;
    　　var len = rawStr.length;
    　　if(len % 2 !== 0) {
  console.error("Illegal Format ASCII Code!");
  　　　　return "";
　　}
　　var curCharCode;
　　var resultStr = [];
　　for (var i = 0; i < len; i = i + 2) {
  　　　　curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
  　　　　resultStr.push(String.fromCharCode(curCharCode));
　　}
　　return resultStr.join("");
},
  buf2hex: function (buffer) {
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
  },
  string2buf: function (str) {
    console.log(str)
    // 首先将字符串转为16进制
    let val = ""
    for (let i = 0; i < str.length; i++) {
      if (val === '') {
        val = str.charCodeAt(i).toString(16)
      } else {
        val += ',' + str.charCodeAt(i).toString(16)
      }
    }
    console.log(val)
    // 将16进制转化为ArrayBuffer
    var hexStr = 'BB0003000100047E';
    var typedArray = new Uint8Array(hexStr.match(/[\da-f]{2}/gi).map   
    (function (h) {
      return parseInt(h, 16)
    }))
    var buffer = typedArray.buffer;
    console.log(buffer)
    return buffer;
  },
  string2bufTest: function (str) {
    console.log(str)
    let val = '' + str
    console.log(val)
    var typedArray = new Uint8Array(val.match(/[\da-f]{2}/gi).map
      (function (h) {
        return parseInt(h, 16)
      }))
    var buffer = typedArray.buffer;
    console.log(buffer)
    return buffer;
  },
  /**
   * 字符串每20个字节分包返回数组
   */
  subPackage: function (str) {
    const packageArray = []
    for (let i = 0; str.length > i; i += 20) {
      packageArray.push(str.substr(i, 20))
    }
    console.log(str)
    console.log(packageArray.join(''))
    return packageArray
  },
  /**
   * 停止搜索附近蓝牙
   */
  stopSearchDevs: function () {
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) { },
    })
  },
  /**
   * 开始连接
   */
  startConnect(deviceId, deviceName = '未知设备') {
    if (this.globalData.BluetoothState) {
      wx.createBLEConnection({
        deviceId: deviceId,
        timeout: 10000, // 10s连接超时
        success: function (res) {
          wx.navigateTo({
            url: `/pages/service/service?deviceId=${deviceId}&deviceName=${deviceName}`,
          })
        },
      })
    }
  },
  /**
   * 断开连接
   */
  endConnect(deviceId) {
    if (this.globalData.BluetoothState) {
      wx.closeBLEConnection({
        deviceId: deviceId,
        success: function (res) {},
      })
    }
  }
  
})